<template>
  <div :class="$style.wrap">
    <CallQuery @showAll="showAllHandle">
      <All v-if="all" @cilckWorkOrder="toWorkOrder" @cilckOrder="toOrder"></All>
      <template v-else>
        <Shop v-if="$isShop()||$isCustomerCare()" @cilckOrder="toOrder"></Shop>
        <Sale v-else-if="$isSale()"></Sale>
        <Finance v-else-if="$isFinance()"></Finance>
        <Client v-else-if="$isClient()||$isSale3() || $isCustomerManagement()" @cilckWorkOrder="toWorkOrder"></Client>
      </template>
    </CallQuery>
    <Dialog :visible.sync="visible" title="电脑放音" :close-on-click-modal="false" destroy-on-close @closed="music={}">
      <div :class="$style['cus-audio']">
        <div :class="$style.desc">
          <span v-if="music.title">客户姓名: {{ music.title }}</span>
          <span v-if="music.artist">接听坐席: {{ music.artist }}</span>
        </div>
        <audio v-if="visible" :src="music.src" controls autoplay></audio>
      </div>
    </Dialog>
    <PhonePlay ref="phonePlay" :voice="voice" :step-time="5" @closed="voice = {}"></PhonePlay>
  </div>
</template>
<script>
import { mapGetters } from 'vuex'
import All from './components/All'
import Client from './components/Client'
import Finance from './components/Finance'
import Sale from './components/Sale'
import Shop from './components/Shop'
import CallQuery from './components/CallQuery'
import { downFileByA } from '@/utils'
import { putRename } from '@/api/telRecord'
import PhonePlay from '@/components/PhonePlay'
import Dialog from '@/components/Dialog'
export default {
  name: 'TelRecord',
  components: {
    CallQuery,
    Shop,
    Sale,
    Finance,
    Client,
    All,
    PhonePlay,
    Dialog
  },
  data() {
    return {
      visible: false,
      music: {},
      all: false,
      xhr: null,
      voice: {}
    }
  },
  computed: {
    ...mapGetters(['user'])
  },
  methods: {
    // 处理录音文件地址
    handleSrc(recordingAddress, row) {
      let baseURL = process.env.VUE_APP_BASE_WAV
      if (this.$dev) {
        baseURL = '/file'
      }
      if (row.callPlatform === '02') {
        return Promise.resolve(`${baseURL}${recordingAddress}`)
      }
      let paths = recordingAddress.split(':')[1].replace(/\.(v|V)3$/, '.wav')
      paths = baseURL + paths
      if (/\.(v|V)3$/.test(recordingAddress)) {
        return putRename(recordingAddress).then(res => {
          return paths
        })
      }
      return Promise.resolve(paths)
    },
    // 话机放音
    playPhone(row) {
      if (this.$store.state.callBar.sign) {
        if (this.$refs.phonePlay.visible) {
          this.$message.error('正在播放录音！')
          return
        }
        if (!row.recordingAddress) {
          this.$message.error('没有录音文件！')
          return
        }
        this.$refs.phonePlay.visible = true
        this.voice = row
      } else {
        this.$message.info('请先签入话务平台！')
      }
    },
    // 播放录音
    palyAudio(row) {
      if (this.visible) {
        this.$message.error('正在播放录音！')
        return
      }
      if (!row.recordingAddress) {
        this.$message.error('没有录音文件！')
        return
      }
      this.$set(this.music, 'artist', '坐席(' + row.callerName + ')')
      this.$set(this.music, 'title', row.customerName || '')
      this.handleSrc(row.recordingAddress, row).then(src => {
        this.$set(this.music, 'src', src)
        this.visible = true
      })
      // this.ajaxDownLoad(row.recordingAddress).then(res => {
      //   this.$set(this.music, 'src', res)
      //   this.visible = true
      // })
    },
    downAudio(row) {
      if (!row.recordingAddress) {
        this.$message.error('没有录音文件！')
        return
      }
      this.handleSrc(row.recordingAddress, row).then(src => {
        downFileByA(src, `${row.customerName}-${row.customerPhone}-${row.callDate}.wav`)
      })
    },
    // ajax下载录音文件
    // ajaxDownLoad(recordingAddress) {
    //   const xhr = new XMLHttpRequest()
    //   this.xhr = xhr
    //   xhr.open('GET', this.handleSrc(recordingAddress))
    //   const ajax = new Promise((resolve, reject) => {
    //     xhr.onreadystatechange = () => {
    //       if (xhr.readyState === 4) {
    //         if (xhr.status === 200) {
    //           const b = new Blob([xhr.response], {type: 'audio/x-wav'})
    //           const audioData = new FileReader()
    //           audioData.readAsDataURL(b)
    //           audioData.onload = () => {
    //             resolve(audioData.result)
    //           }
    //         } else {
    //           reject(new Error('下载失败！'))
    //         }
    //       }
    //     }
    //   })
    //   xhr.send()
    //   return ajax
    // },
    // 选择全部
    showAllHandle(v) {
      this.all = v
    },
    // 跳转到工单
    toWorkOrder(row) {
      if (row.workOrderNo) {
        this.$router.push({
          name: 'QueryOrderDetails',
          query: { workOrderNo: row.workOrderNo, form: 'telRecord' }
        })
      }
    },
    // 跳转到订单
    toOrder(row) {
      if (row.callOrderCode) {
        if (row.callOnlinePlatformCode) {
          this.$router.push({
            name: 'InfoDataGoods',
            query: { callOrderCode: row.callOrderCode, form: 'telRecord' }
          })
        } else {
          this.$router.push({
            name: 'InfoDataShopRetail',
            query: { callOrderCode: row.callOrderCode, form: 'telRecord' }
          })
        }
      }
    }
  }
}
</script>
<style lang='scss' module>
.wrap{
  & [class*="table-button-box"]{
    [class*="el-button"]{
      padding: 0 !important;
    }
  }
}
  .cus-audio{
    &>audio{
      width: 100%;
      height: 35px;
    }
    .desc{
      padding: 5px 10px;
      &>span{
        font-size: 14px;
      }
      &>{
        span+span{
          margin-left: 5px;
        }
      }
    }
  }
</style>
